<?php
namespace app\wechat\controller;

use app\wechat\model\HTTPModel;
use think\Cache;


class Common extends HTTPModel
{
    
    //public $wechat_url = 'http://172.21.50.193';
    protected $hostname = 'http://121.8.227.34/cgi-bin';
    private $corpid = 'wl79d1b0af16';
    private $corpsecret = 'loWNtjSQsq0uUDsb0QuDjqTA8d3Wt-3bBlgHoAcU7DQ';
    
    public function getOauthUrl($STATE = 'STATE'){
        $redirect_uri = urlencode(url('@wechat/callback/index','','',TRUE));
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='. $this->corpid .'&redirect_uri='. $redirect_uri .'&response_type=code&scope=snsapi_base&state='.$STATE.'#wechat_redirect';
        return $url;
    }
    
    public function getAccessToken(){
        $access_token = Cache::get('AccessToken');
        if($access_token){
            return $access_token['access_token'];
        }
        $param = ['query' => ['corpid' => $this->corpid, 'corpsecret' => $this->corpsecret]] ;
        $resp = $this->wechatHttp('/gettoken' , $param);
        $resp = json_decode($resp, TRUE);
        if($resp['errcode'] == 0){
            Cache::set('AccessToken',$resp,7000);
            return $resp['access_token'];
        }else{
            return false;
        }
    }

    public function getJsapiTicket(){
        $param = ['query' => ['access_token' => $this->getAccessToken()]] ;
        $resp = $this->wechatHttp('/get_jsapi_ticket' , $param);
        $resp = json_decode($resp, TRUE);
        if($resp['errcode'] == 0){
            Cache::set('JsapiTicket',$resp,7000);
            return $resp['ticket'];
        }else{
            return false;
        }
    }
     // 获取签名
    public function getSignPackage() {
        // 获取ticket
        $ticket = $this->getJsapiTicket();
        
        // 该url为调用jssdk接口的url
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        // 生成时间戳
        $timestamp = time();
        // 生成随机字符串
        $nonceStr = $this->createNoncestr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序 j -> n -> t -> u
        $string = "jsapi_ticket=$ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array (
            "appId" => $this->corpid,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "ticket" => $ticket,
        );
        // 返回数据给前端
        return $signPackage;
    }
    // 创建随机字符串
    public function createNoncestr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for($i = 0; $i < $length; $i ++) {
            $str .= substr ( $chars, mt_rand ( 0, strlen ( $chars ) - 1 ), 1 );
        }
        return $str;
    }

    public function getArrayUniqueByKeys($list,$name){
        $arr_out =array();
        foreach($list as $arr){
            foreach($arr as $k => $v){
                $key_out = $v[$name]; //提取内部一维数组的key(name age)作为外部数组的键

                if(array_key_exists($key_out,$arr_out)){
                    //print_r($arr[$k]);echo '||||';
                    continue;
                }
                else{
                    $arr_out[$key_out] = $arr[$k]; //以key_out作为外部数组的键
                    $arr_wish[] = $arr[$k];  //实现二维数组唯一性
                }
            }
        }
        return $arr_wish;
    }
}
    